package com.bos.service.imp;

import com.bos.dao.IStaffDao;
import com.bos.domain.Staff;
import com.bos.service.IStaffService;
import com.bos.utils.PageBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

/**
 * @author Administrator
 */
@Service
@Transactional
public class IStaffServiceImp implements IStaffService {

    @Autowired
    IStaffDao staffDao;

    @Override
    public void addStaff(Staff staff) {
        staffDao.save(staff);
    }

    @Override
    public void pageQuery(PageBean page) {
        staffDao.pageQuery(page);
    }

    @Override
    public void deleteBatch(String ids) {
        String decode = null;
        try {
            decode = URLDecoder.decode(ids, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException("不支持该类型编码");
        }
        decode=decode.substring(0,decode.length()-1);
        String[] staffIDs = decode.split(",");
        for (int i = 0; i < staffIDs.length; i++) {
            staffDao.executeUpdate("staff.delete",staffIDs[i]);
        }
    }

    @Override
    public void restoreBatch(String ids) {
        String decode = null;
        try {
            decode = URLDecoder.decode(ids, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            throw new RuntimeException("不支持该url类型编码");
        }
        decode=decode.substring(0,decode.length()-1);
        System.out.println(decode);
        String[] staffIDs = decode.split(",");
        for (int i = 0; i < staffIDs.length; i++) {
            staffDao.executeUpdate("staff.restore",staffIDs[i]);
        }
    }

    @Override
    public void editStaff(Staff newStaff) {
        Staff oldStaff = staffDao.findById(newStaff.getId());
        updateOldStaff(newStaff, oldStaff);
        staffDao.update(oldStaff);
    }

    private void updateOldStaff(Staff newStaff, Staff oldStaff) {
        oldStaff.setId(newStaff.getId());
        oldStaff.setName(newStaff.getName());
        oldStaff.setTelephone(newStaff.getTelephone());
        oldStaff.setStation(newStaff.getStation());
        oldStaff.setHaspda(newStaff.getHaspda());
        oldStaff.setStandard(newStaff.getStandard());
    }

    @Override
    public List<Staff> findAll() {
        return staffDao.findAll();
    }

}
